<?php

namespace app\modules\user\services;

use app\common\services\BaseService;
use app\models\UserAddress;
use app\modules\user\forms\address\AddressForm;

class AddressService extends BaseService{

    /**
     * 搜索
     * @return UserAddress[]
     */
    public static function search(){
        return UserAddress::findAll(['user_id'=>\Yii::$app->getModule("user")->get("user")->getId()]);
    }

    /**
     * 创建
     * @param AddressForm $form
     * @return bool
     * @throws \Throwable
     */
    public static function create(AddressForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = new UserAddress();
        $model->setAttributes($form->getAttributes(),false);
        return $model->insert() !== false;
    }

    /**
     * 获取信息
     * @param $id
     * @return null|UserAddress
     * @throws \yii\base\InvalidConfigException
     */
    public static function getInfoById($id){
        return UserAddress::findOne(['address_id'=>$id,'user_id'=>\Yii::$app->getModule("user")->get("user")->getId()]);
    }

    /**
     * 更新
     * @param AddressForm $form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(AddressForm $form){
        if(!$form->validate()){
            self::setError($form->getFirstFieldError());
            return false;
        }

        $model = UserAddress::findOne(['address_id'=>$form->address_id,'user_id'=>$form->user_id]);
        if(!$model){
            self::setError(\Yii::t("app","地址不存在"));
            return false;
        }

        $model->setAttributes($form->getAttributes(),false);
        return $model->update() !== false;
    }

    /**
     * 删除
     * @param $id
     * @throws \yii\base\InvalidConfigException
     */
    public static function delete($id){
        UserAddress::deleteAll(['address_id'=>$id,'user_id'=>\Yii::$app->getModule("user")->get("user")->getId()]);
    }

}